package com.hzmall.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
public class FileUploadUtil {
    private static Boolean isSuccess = true;

    public static String upload(MultipartFile file,String path){
        String fileName = file.getOriginalFilename();
        String fileExtName = fileName.substring(fileName.lastIndexOf(".")+1); //获取扩展名
        String newFileName = UUID.randomUUID().toString()+"."+fileExtName;
        File files = new File(path);
        if (!files.exists()){
            files.setWritable(true);
            files.mkdirs();
        }
        File targetFile = new File(path,newFileName);
        List<File> fileList = new ArrayList<File>();
        fileList.add(targetFile);
        try {
            file.transferTo(targetFile);
            if (FtpUtil.uploadFile(fileList)){  //上传FTP成功后删除本地文件
                targetFile.delete();
            }
        }catch (Exception e){
           log.error("上传文件异常",e);
           isSuccess = false;
        }
        return newFileName;
    }
}
